package com.atguigu.gulimall.product.service.impl;

import com.sun.xml.internal.bind.v2.TODO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;

@RequiredArgsConstructor
@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    private final CategoryDao categoryDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithSortTree() {
        //查询所有的分类数据
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> levelMenus = entities.stream().filter(s -> s.getCatLevel().equals(1) && s.getShowStatus().equals(1))
                .map(c ->
                {
                    List<CategoryEntity> listWithTreeTree = getChildrens(c.getCatId(), entities);
                    c.setChildren(listWithTreeTree);
                    return c;
                })
                .sorted(Comparator.comparingInt(c->c.getSort() == null ? 0 : c.getSort()))
                .collect(Collectors.toList());
        log.info("返回数据-{}",levelMenus);
        return levelMenus;
    }

    @Override
    public void removeMenuByIds(List<Long> list) {
        //TODO 检查当前删除的菜单，是否有被其他地方引用
        baseMapper.deleteBatchIds(list);
    }

    /**
     * 组织父子结构
     */
    private List<CategoryEntity> getChildrens(Long id, List<CategoryEntity> list){
        List<CategoryEntity>  childrenList= list.stream().filter(c -> c.getParentCid().equals(id)).map(
                c -> {
                    {
                        c.setChildren(getChildrens(c.getCatId(), list));
                        return c;
                    }
                }
        )
        .sorted(Comparator.comparingInt(c->c.getSort() == null ? 0 : c.getSort()))
        .collect(Collectors.toList());
        log.info("子结构-{}",childrenList);
        return childrenList;
    }

}